package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MenuDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private MenuDao menuDao;
    /**
     * 根据用户名查询用户有权访问的菜单项
     * @param username
     * @return
     */
    public List<Menu> findByUsername(String username) {
//        根据用户名查询用户信息
        User user = userDao.findByUsername(username);
        if (user == null) {
            return null;
        }
        Integer userId = user.getId();

        Set<Integer> menuIds = new HashSet<>(); //  存放该用户所有菜单的id

//        获取用户所有角色
        Set<Role> roles = roleDao.findByUserId(userId);
//        遍历角色根据角色Id查询该角色所有菜单id
        for (Role role : roles) {
            Integer roleId = role.getId();
//            获取菜单id
            List<Integer> menus = roleDao.findMenuByRoleId(roleId);
//            将角色id存入set集合 避免角色id重复
            for (Integer menu : menus) {
                menuIds.add(menu);
            }
        }
        Map map = new HashMap();
        map.put("menuIds", menuIds);
//        查询一级菜单信息
        List<Menu> list = menuDao.getLevelOne(map);
//        遍历一级菜单 查询对应二级菜单信息
        for (int i = 0; i < list.size(); i++) {
            Menu menu = list.get(i);
            map.put("id", menu.getId());
            menu.setChildren(menuDao.findLevelTow(map));
        }
        return list;
    }
}
